<?php
/**
 * 机器翻译 WebAPI 接口调用示例
 * 运行前：请先填写Appid、APIKey、APISecret
 *
 * 1.接口文档（必看）：https://www.xfyun.cn/doc/nlp/xftrans/API.html
 * 2.错误码链接：https://www.xfyun.cn/document/error-code （错误码code为5位数字）
 * @author iflytek
 */

namespace app\common;

class Xunf
{
    private static string $appId = '710c8';
    private static string $appSecret = 'NGQzMWMjEzZmQz';
    private static string $appKey = '1e07b387baf0f';

    /**
     * curl 请求
     * @Param string $url
     * @param array $header
     * @param array|string $content
     * @return  array
     *
     * */
    private static function toCurl(string $url,array $header, $content):array
    {
        $ch = curl_init();
        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
            curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        if (is_array($header) && count($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        if (!empty($content)) {
            curl_setopt($ch, CURLOPT_POST, true);
            if (is_array($content)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
            } else if (is_string($content)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
            }
        }
        $response = curl_exec($ch);
        $error = curl_error($ch);
        if ($error) {
            file_put_contents('curl_error.txt',date('Y-m-d H:i:s')." curl出错，错误码:$error".PHP_EOL,8);
            die($error);
        }
        $header = curl_getinfo($ch);

        curl_close($ch);
        return array('header' => $header, 'body' => $response);
    }

    public static function translate(string $text,string $from = 'cn',string $to = 'en'):array
    {
        // 机器翻译接口地址
        $url = "https://itrans.xfyun.cn/v2/its";

        $host = 'itrans.xfyun.cn';

        //body组装
        $body = json_encode(self::getBody( $from, $to, $text));

        // 组装http请求头
        $date = gmdate('D, d M Y H:i:s') . ' GMT';

        $digestBase64 = "SHA-256=" . base64_encode(hash("sha256", $body, true));
        $builder = sprintf("host: %s\ndate: %s\nPOST /v2/its HTTP/1.1\ndigest: %s", $host, $date, $digestBase64);

        $sha = base64_encode(hash_hmac("sha256", $builder, self::$appSecret, true));

        $authorization = sprintf('api_key="%s", algorithm="hmac-sha256", headers="host date request-line digest", signature="%s"', self::$appKey, $sha);

        $header = [
            "Authorization: " . $authorization,
            'Content-Type: application/json',
            'Accept: application/json,version=1.0',
            'Host: '.$host,
            'Date: ' . $date,
            'Digest: ' . $digestBase64
        ];


        $response = self::toCurl($url, $header, $body);

        return json_decode($response['body'],true);
    }

    public static function translateNew(string $text,string $from = 'cn',string $to = 'en'):string
    {
        // 机器翻译接口地址
        $url = "https://itrans.xf-yun.com/v1/its";

        $host = 'itrans.xf-yun.com';

        //body组装
        $body = self::getBodyNew( $from, $to, $text);

        // 组装http请求头
        $date = gmdate('D, d M Y H:i:s') . ' GMT';

        $builder = sprintf("host: %s\ndate: %s\nPOST /v1/its HTTP/1.1", $host, $date);
        $appSec = self::$appSecret;

        $sha = base64_encode(hash_hmac("sha256", $builder, $appSec, true));

        $appKey = self::$appKey;

        $authorization = sprintf('api_key="%s", algorithm="hmac-sha256", headers="host date request-line", signature="%s"', $appKey, $sha);

        $authorization = base64_encode($authorization);

        $header = [
            'Content-Type: application/json',
            'App_Id: '.self::$appId,
            'Host: '.$host,
            'Accept: application/json,version=1.0',
            'Date: '.$date
        ];

        $url .= '?authorization='.$authorization.'&host='.$host.'&date='.$date;


        return httpCurl($url, $body, $header);
    }

    private static function getBody(string $from,string $to,string $text):array
    {
        $common_param = [
            'app_id' => self::$appId
        ];

        $business = [
            'from' => $from,
            'to' => $to,
        ];

        $data = [
            "text" => base64_encode($text)
        ];

        return [
            'common' => $common_param,
            'business' => $business,
            'data' => $data
        ];
    }

    private static function getBodyNew(string $from,string $to,string $text):string
    {

        return json_encode([
            'header'=> [
                'app_id'=> self::$appId,
                'status'=> 3
            ],
            'parameter'=> [
                'its'=> [
                    'from'=> $from,
                    'to'=> $to,
                    'result'=> new \ArrayObject()
                ]
            ],
            'payload'=> [
                'input_data'=> [
                    'encoding'=> "utf8",
                    'status'=> 3,
                    'text'=> base64_encode($text)
                ]
            ]
        ]);
    }


}

